package com.example.document.view

import android.os.Environment
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.blankj.utilcode.util.ToastUtils
import com.example.document.DocumentIntent
import com.example.document.DocumentViewModel
import com.example.document.R
import com.example.lib_base.HttpType
import com.example.lib_base.entity.LocalEntity
import com.example.lib_base.UIState
import kotlinx.coroutines.launch

@Composable
fun LocalPage(navHostController: NavHostController, vm: DocumentViewModel = hiltViewModel()) {
    //获取已下载文件的文件夹
//    val file = BaseApp.context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
    //获取相册图库
    val file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
    val list = remember {
        SnapshotStateList<LocalEntity>()
    }
    //记录选中的名字
    var checkName by remember {
        mutableStateOf("")
    }
    //记录选中的路径
    var checkPath by remember {
        mutableStateOf("")
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnError -> {
                        Log.e("TagA", "读取本地文件失败:${it.msg}")
                    }

                    UIState.OnLoading -> {}
                    is UIState.OnSuccess<*> -> {
                        // Collection<LocalEntity> 包含LocalEntity的集合
                        //list.addAll(it.data as Collection<LocalEntity>)
                        if (it.type == HttpType.DEFAULT) {
                            list.clear()
                            // Collection<LocalEntity> 包含LocalEntity的集合
                            list.addAll(it.data as Collection<LocalEntity>)
                        } else if (it.type == HttpType.UPLOAD) {
                            ToastUtils.showLong("上传成功")
                        }
                    }
                }
            }
        }

        vm.sendIntent(DocumentIntent.ScanFiles(file!!))
    })

    Column(Modifier.padding(10.dp)) {
        Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) {
            Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "", Modifier.clickable {
                navHostController.popBackStack()
            })
            Text(text = "上传文件选择")
            //Text(text = "上传")
            Text(text = "上传", Modifier.clickable {
                vm.sendIntent(DocumentIntent.UploadDocument(checkName, checkPath))
            })
        }
        Spacer(modifier = Modifier.height(10.dp))
        LazyColumn(content = {
            items(list) {
               // LocalItem(entity = it)
                LocalItem(entity = it, it.fileName == checkName) {
                    checkName = it.fileName
                    checkPath = it.path
                }
            }
        }, verticalArrangement = Arrangement.spacedBy(10.dp))
    }
}

@Composable
//fun LocalItem(entity: LocalEntity) {
fun LocalItem(entity: LocalEntity, checked: Boolean, onClick: () -> Unit) {
    Row {
        //Image(painter = painterResource(id = R.drawable.document), contentDescription = "", Modifier.size(50.dp))
//        Box(modifier = Modifier
//            .padding(5.dp)
//            .clickable {
//                onClick()
//            }, contentAlignment = Alignment.TopEnd
        Box(
            modifier = Modifier
                .padding(5.dp)
                .clickable {
                    onClick()
                }, contentAlignment = Alignment.TopEnd
        ) {
            Image(painter = painterResource(id = R.drawable.document), contentDescription = "", Modifier.size(50.dp))
            val img = if (checked) R.drawable.baseline_check_circle_24 else R.drawable.baseline_check_circle_outline_24
            Image(
                painter = painterResource(id = img), contentDescription = "",
                Modifier
                    .size(15.dp)
                    .offset(
                        7.dp,
                        (-7).dp
                    )
            )
        }
        Spacer(modifier = Modifier.width(10.dp))
        Column(Modifier.height(50.dp), verticalArrangement = Arrangement.SpaceBetween) {
            Text(text = entity.fileName)
            Text(
                text = entity.path,
                color = Color.Gray,
                fontSize = 12.sp,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}